package org.railage.server.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.railage.server.entities.User;
import org.railage.server.util.HibernateUtil;

public class UserDAOImpl implements UserDAO {

	private static final Logger log = Logger.getLogger(UserDAOImpl.class);

	public int addUser(User user) {
		Session session = null;
		Transaction transaction;
		int userID = -1;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			userID = (Integer) session.save(user);
			transaction.commit();
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return userID;
	}

	public User getUserByLoginPassword(String login, String password) {
		Session session = null;
		User user = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			Query query = session
					.createQuery("from User where login = :login and password = :password");
			query.setString("login", login);
			query.setString("password", password);
			@SuppressWarnings("unchecked")
			List<User> users = (List<User>) query.list();
			if (users.size() == 1) {
				user = users.get(0);
			} else if (users.size() > 1) {
				throw new Exception(
						"More than one user with identical personal info");
			}
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return user;
	}

	public User getUserByPersonalInfo(String surname, String name,
			String birthday) {
		Session session = null;
		User user = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			Query query = session
					.createQuery("from User where surname = :surname and name = :name and birthday = :birthday");
			query.setString("surname", surname);
			query.setString("name", name);
			query.setString("birthday", birthday);
			@SuppressWarnings("unchecked")
			List<User> users = (List<User>) query.list();
			if (users.size() > 0) {
				user = users.get(0);
				if (users.size() > 1) {
					throw new Exception(
							"More than one user with identical personal info");
				}
			}
		} catch (Exception e) {
			log.error("Error occured during Hibernate session:", e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return user;
	}

}
